package other.system.client.apitool;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import other.system.client.util.ResultBody;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: OA审批模块对接
 * @Author: 黎炎松
 * @Date: 2024/6/12 10:21
 */
public class OAClientUtils {

    // 正式环境 （路径 +  统一维护模版id）
    private static String BASE_URL = "https://oa.tcl.com"; // 正式域名 切换环境需要同步切换 tempIdMap

    public static final Map<String, String> tempIdMap = new HashMap<String, String>(){{
        put("quote", "1910dad1b32e5daa364463743f789170"); // 报价单
        put("contract", "1910da0a3415591568a1dca406b99a26"); // 合同
        put("specialSontract", "1910da8503e2e41738d5fd5444b88278"); // 特殊合同
        put("bid", "1910db05bb807b69213193b41f0be2ce"); // 投标类文件
        put("bid2", "191c0dba2b8b9140f37b7234feaa66ea"); // 投标类文件2 测试使用
        put("sale", "1910db224f9a68cd41373724a41b0141"); // 其它销售类文件
        put("purchase", "1910db98128fca477a23b624e4f96331"); // 零星采购
        put("campaign", "1910dbc5acc3a58aabccb6e4b76bb95c"); // 市场活动 （项目所属部门团队）
    }};

    // todo 发布需切换正式环境
    // 测试环境（路径 +  统一维护模版id）
    //private static String BASE_URL = "https://ep-uat.tcl.com"; // 测试域名
    //public static final Map<String, String> tempIdMap = new HashMap<String, String>(){{
    //    put("quote", "1900bd12bc1ca5dfe4f2a7c4d5a94c89"); // 报价单
    //    put("contract", "1900bc6d21650994d58e7e6431182faf"); // 合同
    //    put("specialSontract", "190a12057208a084f169e914311a2c2b"); // 特殊合同
    //    put("bid", "1900bcf2eec8ebf2211e0c54e6788a3a"); // 投标类文件
    //    put("sale", "1900bc82422b4819ba04889448fa56e2"); // 其它销售类文件
    //    put("purchase", "190070fabbe4b5c705c0b5a42efb04a8"); // 零星采购
    //    put("campaign", "1900710b9a236e92e7545184f79b923a"); // 市场活动 （项目所属部门团队）
    //}};

    private static final Logger logger = LoggerFactory.getLogger();
    public static String PUSH_APPROVAL_URL = BASE_URL + "/api/km-review/kmReviewRestService/addReview"; // 推送审批模块数据
    public static String UP_APPROVAL_URL = BASE_URL + "/api/km-review/kmReviewRestService/updateReviewInfo"; // 修改审批模块数据
    public static String UNDO_APPROVAL_URL = BASE_URL + "/api/km-review/kmReviewRestService/approveProcess"; // 撤销审批模块数据
    public static String UPLOAD_OA_FILE = BASE_URL + "/api/tcl-crm/tclCrmRestService/downFile"; // 上传CRM附件到OA审批附件
    public static String GET_CURRENT_NODE = BASE_URL + "/api/tcl-crm/tclCrmRestService/getCurrentHandlerData?fdId="; // 获取当前正在审批节点的信息
    public static String GET_FILE_URL = BASE_URL + "/api/sys-attachment/sysAttachmentRestService/getDonwloadUrl?fdId="; // 访问附件的访问路径

    public static void main(String[] args) throws CustomConfigException {
    }

    /**
     * 发送post请求
     * @param reqData
     * @param reqUrl
     * @return
     */
    public static ResultBody sendPost(JSONObject reqData, String reqUrl, Boolean isSendFile) {
        logger.info(" sendPost reqUrl = " + reqUrl);
        String encodedString = Base64.getEncoder().encodeToString("crm:crm123456".getBytes());
        CommonData.Builder post = CommonData.newBuilder().callString(reqUrl)
                .callType("POST")
                .header("Authorization", "Basic " + encodedString)
                .formData(reqData);

        // 是否是发送文件
        if (isSendFile) {
            post.formType("formData");
            post.mimeType("multipart/form-data");
        }

        CommonData build = post.build();
        HttpResult execute = CommonHttpClient.instance(20000, 20000).execute(build);
        String result = execute.getResult();

        // 不是json 判断是否是用户名不对 user is not exist
        logger.info(" sendPost result = " + result);
        if (!isJSON(result)) {
            if (result.equals("user is not exist") || result.indexOf("failed") != -1 || result.equals("Read timed out")) {
                return ResultBody.error(result);
            } else {
                Object resultData = result;
                return ResultBody.success(resultData);
            }
        }

        JSONObject response = JSONObject.parseObject(result);
        Boolean success = response.getBoolean("success");
        if ((success == null || !success) && !Objects.equals(response.getInteger("code"), 200)) {
            String errorMsg = response.getString("msg");
            return ResultBody.error(errorMsg);
        }

        return ResultBody.success();
    }

    // 判断是否能正常解析
    public static boolean isJSON(String str) {
        boolean result = false;
        try {
            JSONObject.parseObject(str);
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }




}
